<?php


namespace api\web\controller;


use api\web\model\UserModel;
use api\web\validate\UserValidate;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;

class MoneyController extends RestBaseController
{
   public function money(Request $request)
   {
       $data = input('post.');
       if(empty($data['money']) || $data['money'] <= 0){
           $this->error('金额错误');
       }
       $type = 1;
       $reason  = '充值';

       //开启事务
       Db::startTrans();
       try{
           $user = Db::name('users')->where('id',$request->userId)->inc('money',$data['money'])->update();
           $money_log = add_money_log($request->userId,$data['money'],$reason,$type);

       }catch (\Exception $exception) {

          $this->error($exception->getMessage());
          Db::rollback();
       }
       Db::commit();
       $this->success('充值成功');
   }

    // 充值功能
    public function addMoney(Request $request)
    {
        $data = input('post.');


        $user_id = $request->userId;

        // 验证输入数据
        $validate = new UserValidate();
        if (!$validate->scene('addMoney')->check($data)) {
            return json(['status' => 'error', 'message' => $validate->getError()], 400);
        }

        // 获取充值金额
        $money = $data['money'];
        $reason = '充值';

        Db::startTrans();
        //作用域

        $newBalance = false;
        $addMoney = false;
        try {
            // 调用 common 函数处理充值逻辑
            $newBalance = add_money_log($user_id, $money, $reason, 1);
            $addMoney = Db::name('users')->where('id', $user_id)->update(['money' => $newBalance]);
            Db::commit();
            return json(['status' => 'success', 'message' => '充值成功', 'new_balance' => $newBalance]);
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error('充值失败');
        }

        if($addMoney && $newBalance){
            Db::commit();
        }else{
            Db::rollback();
            $this->error('充值失败');
        }
    }
//    public function get_transaction_logs(Request $request)
//    {
//        // 查询用户的流水记录
//        $logs = Db::name('money_log')
//            ->where('user_id', $request->userId)
//            ->order('create_time', 'desc')
//            ->select();
//
//        if (!$logs) {
//            $this->error('没有记录');
//        }
//
//        return $logs;
//    }

// 查询流水记录
    public function getTransactionLogs(Request $request)
    {

        $user_id = $request->userId;

        try {
            // 调用 common 函数查询流水记录
            $logs = get_transaction_logs($user_id);

            return success('查询成功',$logs);
        } catch (\Exception $e) {
            return error('查询失败');
        }
    }
    }

